<?php
defined('OA_LIB_PATH') || define('OA_LIB_PATH', '/opt/op/OALib');
defined('OPEN_LIB_PATH') || define('OPEN_LIB_PATH', '/opt/op/OpenLib');

require_once OA_LIB_PATH . '/util/config/Config.php';
require_once OA_LIB_PATH . '/util/model/OpModel.php';
require_once OA_LIB_PATH . '/util/model/OpDbModel.php';
require_once OA_LIB_PATH . '/util/model/OpTableModel.php';
require_once OPEN_LIB_PATH . '/open/models/common.php';
require_once OPEN_LIB_PATH . '/open/models/OaCodeModel.php';
require_once 'Date.php';
require_once 'Log.php';

$logger = Log::factory('console', '', '', array(
    'lineFormat' => '[%1$s] [%3$s] %5$s(%6$s): %4$s',
    'timeFormat' => '%Y-%m-%d %H:%M:%S'
), PEAR_LOG_INFO);
$dbConfig = Oa_Util_Config::getSingleDbConfig(OAII_CUST_DB_CLUSTER_ID);
$dbOAIICust = oci_connect($dbConfig['user'], $dbConfig['pass'], 
	"{$dbConfig['host']}:{$dbConfig['port']}/{$dbConfig['name']}", 'AL32UTF8');
if (!$dbOAIICust) {
    $e = oci_error();
    $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
    exit();
}
$dbConfig = Oa_Util_Config::getSingleDbConfig(OAII_CODE_DB_CLUSTER_ID);
$dbOAIICode = oci_connect($dbConfig['user'], $dbConfig['pass'], 
	"{$dbConfig['host']}:{$dbConfig['port']}/{$dbConfig['name']}", 'AL32UTF8');
if (!$dbOAIICode) {
    $e = oci_error();
    $this->_logger->log("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
    exit();
}
$codeModel = new OaCodeModel($logger);

function importCompany($companyId, $checkConflict = true)
{
    global $logger;
    global $dbOAIICust;
    global $codeModel;
    
    $sql = "SELECT SP_ID,STATUS,SP_NAME,SP_CODE,NOTES,
    	TO_CHAR(UPDATETIME, 'YYYY-MM-DD HH24:MI:SS') AS UPDATETIME 
    	FROM TBCODESP WHERE SP_CODE=:companyId";
    $st = oci_parse($dbOAIICust, $sql);
    oci_bind_by_name($st, ':companyId', $companyId);
    if (!oci_execute($st)) {
        $e = oci_error($st);
        $logger->err("oci_execute failed: code-{$e['code']} message-{$e['message']} sql-{$e['sqltext']}");
        return false;
    }
    $sp = oci_fetch_assoc($st);
    if (!$sp) {
        $logger->err("company not exists: company-$companyId");
        return false;
    }
    $company = $codeModel->getCompany($companyId, OaAppModel::APP_CONFIG_ENV_PRODUCTION);
    if ($checkConflict) {
	    if ($company && $company['SP_NAME'] != $sp['SP_NAME']) {
	        $logger->err("company name conflicted: company-$companyId code_name-{$company['SP_NAME']} cust_name-{$sp['SP_NAME']}");
	        return false;
	    }
	    $companyByName = $codeModel->getCompanyByName($sp['SP_NAME'], OaAppModel::APP_CONFIG_ENV_PRODUCTION);
	    if ($companyByName && $companyByName['SP_ID'] != $sp['SP_CODE']) {
	        $logger->err("company id conflicted: company-{$sp['SP_NAME']} code_id-{$companyByName['SP_ID']} cust_id-{$sp['SP_CODE']}");
	        return false;
	    }
    }
    if ($company) {
    	$logger->info("company already imported: company-$companyId");
    	return true;
    }
    if (!$codeModel->addCompany($sp['SP_CODE'], $sp['SP_NAME'], 
        $sp['STATUS'] + 1, $sp['NOTES'], array(
            'IS_FROM_OA' => 2,
            'UPDATETIME' => $sp['UPDATETIME']
        ), OaAppModel::APP_CONFIG_ENV_PRODUCTION)) {
        $logger->err("add company failed: company-$companyId");
        return false;
    }
    return true;
}

function deleteCompany($companyId)
{
    global $logger;
    global $dbOAIICode;
    global $codeModel;
    
    $company = $codeModel->getCompany($companyId, OaAppModel::APP_CONFIG_ENV_PRODUCTION);
    if (!$company) {
        $logger->err("company not exists: company-$companyId");
        return false;
    }
    if ($company['IS_FROM_OA'] != 2) {
        $logger->err("company is from oa: company-$companyId");
        return false;
    }
    $sql = "DELETE FROM TB_SP WHERE SP_ID=:companyId";
    $st = oci_parse($dbOAIICode, $sql);
    oci_bind_by_name($st, ':companyId', $companyId);
    if (!oci_execute($st)) {
        $e = oci_error($st);
        $logger->err("oci_execute failed: code-{$e['code']} message-{$e['message']} sql-{$e['sqltext']}");
        continue;
    }
    return true;
}
